package com.netty.echo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

public class EchoServer {
	private final int port;

	public EchoServer(int port) {
		this.port = port;
	}

	public static void main(String[] args) throws InterruptedException {
		if (args.length != 1) {
			System.err.println(EchoServer.class.getSimpleName());
		}
//		int port = Integer.parseInt(args[0]);
		int port = Integer.parseInt("8080");
		new EchoServer(port).start();
	}

	public void start() throws InterruptedException {
		final EchoServerHandler serverHandler = new EchoServerHandler();
		// 1
		NioEventLoopGroup group = new NioEventLoopGroup();
		try {
			// 2
			ServerBootstrap b = new ServerBootstrap();
			b.group(group)
					.channel(NioServerSocketChannel.class)// 3
					.localAddress(new InetSocketAddress(port)) // 4
					.childHandler(new ChannelInitializer<SocketChannel>() { // 5
						@Override
						protected void initChannel(SocketChannel ch) throws Exception {
							ch.pipeline().addLast(serverHandler);
						}
					});
			ChannelFuture sync = b.bind().sync(); // 6
			// 获取 Channel 的 CloseFuture 并阻塞当前线程直到完成
			sync.channel().closeFuture().sync();// 7
		} finally {
			group.shutdownGracefully().sync();// 8
		}
	}

}
